package com.icim.handler;

import com.icim.util.UploadFTP;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.sftp.SftpFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.MalformedURLException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.net.URL;
/**
 * Created by xxd on 2017/11/15.
 */
@Component
@PropertySource("classpath:filePaths.properties")
public class sendFTP {
    @Value("${generateXMLPath}")
    private String generateXMLPath;
    @Value("${filepathTo}")
    private String filePathTo;

    @Value("${generateXMLBOEPath}")
    private String generateXMLBOEPath;
    @Value("${sendPath}")
    private String sendPath;
    @Value("${cpoyPath}")
    private String cpoyPath;

    @Value("${FTP.url}")
    private String ftpUrl;
    @Value("${FTP.username}")
    private String ftpUserName;
    @Value("${FTP.password}")
    private String ftpPassWord;
    @Value("${FTP.path}")
    private String ftpPath;

    //获得目录下所有的 tar档信息
    public List<String> queryTar(String path, List<String> fileList) {
        File dataDirFile = new File(path);
        File[] files = dataDirFile.listFiles();
        for (File fileIndex : files) {
            if (fileIndex.isDirectory()) {
                queryTar(fileIndex.getPath(),fileList);
            } else {
                int num = fileIndex.getAbsolutePath().lastIndexOf(".");
                String extension = fileIndex.getAbsolutePath().substring(num + 1);
                if (extension.equals("tar")) {
                    fileList.add(fileIndex.getAbsolutePath().replace("\\","/"));
                }
            }
        }
        return fileList;
    }

    public void uploadFTP(){
        String patha = generateXMLPath;
        // String filepathTo = copyPathTo;
        String filepathTo = filePathTo;  //linu目录下
        List<String> fileList = new ArrayList<String>();
        List<String>  tarFiles = queryTar(patha,fileList);

        for(int i = 0; i < tarFiles.size(); i++) {
            String filePath = tarFiles.get(i);
            String[] filePathStr = filePath.split("/");
            String fileName = filePathStr[filePathStr.length - 1];//tar档的名字
            String parentFileName = filePathStr[filePathStr.length-2];//时间目录的名字
            UploadFTP.upLoadFromProduction(ftpUrl,ftpUserName,ftpPassWord,ftpPath,fileName,filePath);
            try{
                String[] fp = filePath.split("/");
                //to的地方创建一个父文件夹
                String toFileName = filepathTo+"/"+parentFileName + "/" + fp[fp.length-1];
                File file = new File(filePath);
                File toFile = new File(toFileName);
                File fileParent = toFile.getParentFile();
                if(!fileParent.exists()){
                    fileParent.mkdirs();
                }

                toFile.createNewFile();
                fileChannelCopy(file,toFile);
                //删除原文件
                file.delete();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //删除空目录
        File f = new File(patha);
        ShowDir(f);
        return;

    /*    * @param host FTP服务器hostname
     * //@param port FTP服务器端口
     * @param username FTP登录账号
     * @param password FTP登录密码
     * @param basePath FTP服务器基础目录
     * @param filePath FTP服务器文件存放路径。例如分日期存放：/2015/01/01。文件的路径为basePath+filePath
                * @param filename 上传到FTP服务器上的文件名
                * @param input 输入流*/
    }


    //从2.7共享文件夹复制文件到200本地
    public void BOEcopyXml(){
        //1.循环遍历共享文件夹
        String path = generateXMLBOEPath;
        String sendPathto = sendPath;
        String copyPath = cpoyPath;
        ArrayList<File> fileList = new ArrayList<File>();
        ArrayList<File> fileLists = queryFile(path,fileList);
        for (int i = 0; i < fileLists.size();i++){
            File file = fileLists.get(i);
            mvFile(file,sendPathto,copyPath);
        }
    }


    //删除空文件夹
    public void ShowDir(File f) {
        for (File f1 : f.listFiles()) {
            if (f1.isDirectory()) {
                ShowDir(f1);//一直递归到最后的目录
                if (f1.listFiles().length == 0) {//如果是文件夹里面没有文件证明是空文件，进行删除
                    f1.delete();
                }
            }
        }
    }


    //通过文件管道复制文件
    public void fileChannelCopy(File s, File t) {
        FileInputStream fi = null;
        FileOutputStream fo = null;
        FileChannel in = null;
        FileChannel out = null;
        try {
            fi = new FileInputStream(s);
            fo = new FileOutputStream(t);
            in = fi.getChannel();//得到对应的文件通道
            out = fo.getChannel();//得到对应的文件通道
            in.transferTo(0, in.size(), out);//连接两个通道，并且从in通道读取，然后写入out通道
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fi.close();
                in.close();
                fo.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void connectLinux() {
        SshClient client = new SshClient();
        try {
            client.connect("10.201.11.200");//"此处是Linux服务器IP"
            //设置用户名和密码
            PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
            pwd.setUsername("root");
            pwd.setPassword("root");
            int result = client.authenticate(pwd);
            if (result == AuthenticationProtocolState.COMPLETE) {//如果连接完成
                System.out.println("===============" + result);
                List<SftpFile> list = client.openSftpClient().ls("/etc/mail/");
                for (SftpFile f : list) {
                    System.out.println(f.getFilename());
                    System.out.println(f.getAbsolutePath());
                    if (f.getFilename().equals("aliases")) {
                        OutputStream os = new FileOutputStream("d:/mail/" + f.getFilename());
                        client.openSftpClient().get("/etc/mail/aliases", os);
                        //以行为单位读取文件start
                        File file = new File("d:/mail/aliases");
                        BufferedReader reader = null;
                        try {
                            System.out.println("以行为单位读取文件内容，一次读一整行：");
                            reader = new BufferedReader(new FileReader(file));
                            String tempString = null;
                            int line = 1;//行号
                            //一次读入一行，直到读入null为文件结束
                            while ((tempString = reader.readLine()) != null) {
                                //显示行号
                                System.out.println("line " + line + ": " + tempString);
                                line++;
                            }
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if (reader != null) {
                                try {
                                    reader.close();
                                } catch (IOException e1) {
                                }
                            }
                        }
                        //以行为单位读取文件end
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public ArrayList<File> queryFile(String path,ArrayList<File> fileList) {
        File dataDirFile = new File(path);
        File[] files = dataDirFile.listFiles();
        for (File fileIndex : files) {
            if (fileIndex.isDirectory()) {
                queryFile(fileIndex.getPath(),fileList);
            } else {
                fileList.add(fileIndex);
            }
        }
        return fileList;
    }

    public void mvFile(File file,String toPath,String copyPath){
        //备份文件
        try {
            String filePath = file.getPath();
            String[] fp = filePath.split("\\\\");
            //目标目录 linux
            String toFileName = toPath + "\\" + fp[fp.length-1];
            File toFile = new File(toFileName);
            File fileParent = toFile.getParentFile();
            if(!fileParent.exists()){
                fileParent.mkdirs();
            }
            toFile.createNewFile();
            fileChannelCopy(file,toFile);

            //copy目录 window
            String toFileName2 = copyPath + "/" + fp[fp.length-1];
            File toFile2 = new File(toFileName2);
            File fileParent2 = toFile2.getParentFile();
            if(!fileParent2.exists()){
                fileParent2.mkdirs();
            }
            toFile2.createNewFile();
            fileChannelCopy(file,toFile2);

            //删除原文件
            boolean f = file.delete();
            System.out.println(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
